<!--
  Gz 通用状态切换按钮，  支持switch和badge两个格式， 根据权限进行判断

  @author will
  @site https://pt.jdyd.xyz
  @date 2021/5/8 07:18
-->
<template>
  <div>
    <template v-if="!showSwitchType">
      <div v-if="state == 0">
        <a-badge status="error" text="停用" />
      </div>
      <div v-else-if="state == 1">
        <a-badge status="processing" text="启用" />
      </div>
      <div v-else>
        <a-badge status="warning" text="未知" />
      </div>
    </template>

    <template v-if="showSwitchType">
      <!-- 启用停用文字去掉 -->
      <a-switch checked-children="" un-checked-children="" :checked="data.switchChecked" :disabled="props.disabled" @change="onChangeInner" />
    </template>
  </div>
</template>

<script lang="ts" setup>
import {reactive,watch,onMounted,nextTick} from 'vue'

  // 传递数据参数 ( 父-->子 参数 )
 const  props =defineProps ({
    state: { type: Number, default: -1 }, // 初始化列表数据， 默认true
    showSwitchType: { type: Boolean, default: false }, // 默认 badge
    onChange: { type: Function, default: (checked) => { return new Promise<void>(resolve => { resolve( ) }) } }, // change回调事件
    disabled:{type:Boolean,default:false}
  })

      const data = reactive({
          switchChecked : false
      })


    // 监听 props属性
    watch(() => props.state, function(o, n){
          data.switchChecked = props.state === 1
        }
    )


  onMounted(()=>{
    data.switchChecked = props.state === 1
  })


  function  onChangeInner(checked) {

      data.switchChecked = checked

      // 回调输出 0 和 1; 成功不需要处理， 失败需要经状态变更为原始状态
      props.onChange((checked ? 1 : 0)).then().catch(res => {
       nextTick(() => { data.switchChecked = !checked })
      })
    }
</script>
